<?php
namespace AdminBundle\Repository;


use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class AuthGroupRepository extends BaseRepository
{
    public function pageQuery($_params, $page)
    {
        $sql = <<<EOF
select 
id, name, note, is_enabled as isEnabled, ctime, create_user as createUser
from auth_group 
where 1=1 
EOF;
        $params = array();
        if (!empty($_params)) {
            /*            if (isset($_params['starttime'])) {
                            $sql .= ' and ctime > :starttime ';
                            $params['starttime'] = $_params['starttime'];
                        }
                        if (isset($_params['endtime'])) {
                            $sql .= ' and ctime < :endtime ';
                            $params['endtime'] = $_params['endtime'];
                        }*/
            if (isset($_params['keyword']) && !empty($_params['keyword'])) {
                $sql .= ' and name like :keyword ';
                $params['keyword'] = '%' . $_params['keyword'] . '%';
            }
        }

        $sql .= ' ORDER BY id DESC';

        return $this->pageWithRawSql($sql, $params, $page);
    }

    /**
     * 撤消组已经分配的角色
     * @param $groupId
     * @param array $roleIds
     * @return bool
     * @throws \Exception
     */
    public function revokeGroupRole($groupId, $roleIds = [])
    {
        $params = ['group_id' => $groupId];
        $sql = "delete from auth_link_group_roles where group_id = :group_id ";
        if (!empty($roleIds)) {
            $sql .= " and role_id not in (" . implode(",", $roleIds) . ")";
        }

        return $this->rawExecute($sql, $params);
    }

    public function loadByGroupIdAndRoleId($groupId, $roleId)
    {
        $sql = "select * from auth_link_group_roles where group_id = :group_id and role_id = :role_id";
        $params = ['group_id' => $groupId, 'role_id' => $roleId];
        return $this->rawQuery($sql, $params);
    }

}
